pacman::p_load(tidyverse,readr)

setwd("")#set personal working directory

capitalize <- function(string) {
  substr(string, 1, 1) <- toupper(substr(string, 1, 1))
  string
}

dta.party<-readr::read_rds("morning-consult.rds")%>%#using .rds because .csv gives trouble for some reason
  dplyr::select(-id)%>%
  group_by(Date, party)%>%
  dplyr::summarize(across(everything(), ~ mean(.x, na.rm=T)))%>%
  setNames(c("Date", "Party", "Traits", "Background", "Demographics", "Electability", "Policy", "Ideology", "Socgroups", "Otherperson"))

#subset by party
dta.party.reps <- dta.party %>%
  filter(., Party == "R") %>%
  dplyr::select(-Party)
dta.party.dems <- dta.party %>%
  filter(., Party == "D")  %>%
  dplyr::select(-Party)

#visualize
plot.reasons <- function(dta, reasons, smoothness, party_demonym) {
  par(mar = c(3.1, 5.1, 4.1, 2.1))
  point.types <- c(19, 18, 17, 15)
  max.point <- .6
  
  plot(dta$Date,
       c(1:length(dta$Date)),
       type = "n",
       main = paste0(party_demonym, ": Reasons for 2016 Primary\nCandidate Support"),
       ylim = c(0,max.point),
       yaxt = "n",
       xlab = "",
       ylab = "Percent of Respondents\nReferencing Trait",
       bty  = "l"
  )
  
  segments(dta$Date[1] - 100,
           seq(0,max.point,.1),
           dta$Date[dim(dta)[1]] + 10,
           seq(0,max.point,.1),
           col = "lightgray",
           lty = "dotted")
  
  labs <- paste0(seq(0, 100 * max.point, 10), "%")
  labs[c(F, T)] <- ""
  
  axis(2,
       labels = labs,
       at = seq(0, max.point, .1),
       xpd = T,
       las = 2
  )
  
  
  for (i in 1:length(reasons)) {
    lines(dta$Date,
          forecast::ma(dta[, reasons[i]], smoothness),
          type = "o",
          pch = point.types[i])
  }

  legend(x = "topright",
         xjust = 1,
         yjust = 1,
         legend = capitalize(tolower(reasons)),
         pch = point.types[1:length(reasons)],
         bty = "n",
         y.intersp = .5)
}

pdf("figureA5.pdf")
par(mfrow = c(2,2))
plot.reasons(dta.party.dems, 
             c("Traits", 
               "Background"), 2, "Democrats")
plot.reasons(dta.party.dems,
             c("Demographics", 
               "Electability"), 2, "Democrats")
plot.reasons(dta.party.dems,
             c("Policy", 
               "Ideology"), 2, "Democrats")
plot.reasons(dta.party.dems,
             c("Socgroups", 
               "Otherperson"), 2, "Democrats")
dev.off()

pdf("figureA4.pdf")
par(mfrow = c(2,2))
plot.reasons(dta.party.reps, 
             c("Traits", 
               "Background"), 2, "Republicans")
plot.reasons(dta.party.reps,
             c("Demographics", 
               "Electability"), 2, "Republicans")
plot.reasons(dta.party.reps,
             c("Policy", 
               "Ideology"), 2, "Republicans")
plot.reasons(dta.party.reps,
             c("Socgroups", 
               "Otherperson"), 2, "Republicans")
dev.off()
